var express = require("express");
var router = express.Router();
//引入模型
var Category = require("../models/Category");
var Content = require("../models/Content");
const marked = require('marked');
var data = null;
router.use(function(req, res, next){
	data = {
		userInfo: req.userInfo,
		categories: []
	}
	Category.find().then(function(categories){
		if(categories){
			data.categories = categories;
			next();	
		}else{
			router.render("admin/error",{
				userInfo: req.userInfo,
				message: "分类未找到"
			})
			return;
		}
	})
})
router.get("/", function(req, res, next){
	// res.send("首页");
	//加载index.html
	// console.log(req.userInfo)

	data.page= Number(req.query.page || 1);
	data.limit= 4;
	data.pages= 0;
	data.count= 0;
	data.category = req.query.category || ""
	
	var where = {};
	if(data.category){
		where.category = data.category;
	}

	Content.where(where).count().then(function(count){
		data.count = count;
		//计算总页数
		data.pages = Math.ceil(data.count / data.limit);
		//取值不能超过pages
		data.page = Math.min(data.page, data.pages);
		//取值不能小于1
		data.page = Math.max(data.page, 1);
		//要根据page的值动态进行计算
		var skip = (data.page - 1) * data.limit;
		return Content.where(where).find().sort({_id: -1}).limit(data.limit).skip(skip).populate(["category", "author"]);
	}).then(function(contents){
		data.contents =contents;
		//在这里将用户数据分配给各个模板
		// console.log(data);
		res.render("main/index", data);
	})
})
/* 
	点击阅读全文 通过 这个路由进入 全文浏览页面
*/
router.get("/view", function(req, res){
	var contentId = req.query.contentId || "";
	Content.findOne({
		_id: contentId
	}).then(function(content){
		data.content = content
		// data.content.content=req.markdown.makeHtml(content.content)
		// data.content.content=marked(content.content)
		content.views ++;
		content.save()
		// content.comments.reverse();
		res.render("main/view", data)
	})
})
module.exports = router;